var ImageFile;
function listenFileSelect() {
    // listen for file selection 
    var fileInput = document.getElementById("mypicInput"); // pointer #1 
    // When a change happens to the File Chooser Input 
    fileInput.addEventListener('change', function (e) {
        ImageFile = e.target.files[0];   //Global variable 
        var imageurl = URL.createObjectURL(ImageFile);
        console.log(imageurl);
        updateImage(imageurl);
    })

}
listenFileSelect();

function updateImage(imageurl) {
    const image = document.getElementById("mypic-goes-here"); // pointer #2 
    image.src = imageurl; // Display this image 
}

function savePost() {
    // Gather the data from the form 
    var calorieData = document.getElementById('calorieInput').value;
    var details = document.getElementById('detailsText').value;
    var image = document.getElementById('mypicInput').files[0];

    const now = new Date();
    const dformatted = now.toLocaleString('en-US', {
        weekday: 'short',  // "Monday", "Tuesday", etc. 
        year: 'numeric',  // "2021", "2022", etc. 
        month: 'short',    // "January", "February", etc. 
        day: 'numeric',   // 1, 2, 3, etc. 
        hour: 'numeric',  // 12 AM, 1 PM, etc. 
        minute: 'numeric',
        second: 'numeric'
    });

    const editID = document.getElementById('editID').value;
    if(!editID){
        var formData = {
            date: dformatted,       //save the date 
            calories: calorieData,  //save the calorie entered 
            details: details,
            imageName: image.name // Store image name as a reference 
        };
    
        addToPostHistory(formData);
        location.href = "../history.html";
    }else{
        const user = JSON.parse(localStorage.getItem("loggedinUser"));
        const users = JSON.parse(localStorage.getItem("users"));
        const person = users.find(u => u.email === user["email"]);

        person.count = Number(person.count) - Number(person.history[editID].calories)+ Number(calorieData);

        person.history[editID].data = dformatted;
        person.history[editID].details = details;
        person.history[editID].calories = calorieData;
        if(image){
            //image was changed
            person.history[editID].imageName = image.name;
        }

        localStorage.setItem("users", JSON.stringify(users));
        alert("Your post has been updated!");
        location.href="../history.html";
    }
}

function addToPostHistory(data) {
    var user = JSON.parse(localStorage.getItem("loggedinUser"));
    if (user) {
        var users = JSON.parse(localStorage.getItem("users"));
        var email = user["email"];  //email of who is logged in 

        const person = users.find(u => u.email === email);
        if (person.history === null)      //if there are no users yet 
            person.history = [];          //initialize it to empty 

        // pushes it to the "person" object 
        person.history.push(data);

        localStorage.setItem("users", JSON.stringify(users));
        addCountLocalStorage(data.calories);
        alert('Data saved successfully!');

    } else {
        console.log("No one is logged in");
    }
}

function addCountLocalStorage(value) {
    var user = JSON.parse(localStorage.getItem("loggedinUser"));
    var users = JSON.parse(localStorage.getItem("users"));
    const person = users.find(u => u.email === user["email"]);
    person.count = Number(person.count) + Number(value);
    localStorage.setItem("users", JSON.stringify(users));
}

function checkEdit() {
    var params = new URLSearchParams(window.location.search);
    const id = params.get("id");
    if (id) {
        const user = JSON.parse(localStorage.getItem("loggedinUser"));
        const users = JSON.parse(localStorage.getItem("users"));
        const person = users.find(u => u.email === user["email"]);

        document.getElementById("postHeader").innerHTML = "Edit your Post from"+person.history[id].data;
        document.getElementById("postButton").innerHTML = "Update Post";

        document.getElementById("calorieInput").value = person.history[id].calories;
        document.getElementById("detailsText").value = person.history[id].details;

        updateImage("../images/"+person.history[id].imageName);

        document.getElementById("editID").value = id;

    }
}
checkEdit(); 